//
//  WYMomentItemViewModel.m
//  FriendCircleDemo
//
//  Created by mac on 2018/9/27.
//  Copyright © 2018年 WY. All rights reserved.
//

#import "WYMomentItemViewModel.h"
#import "WYMomentHelper.h"


@interface WYMomentItemViewModel ()
/// 点赞+评论列表 （设计为 可变数组 后期需要添加东西）
@property (nonatomic, readwrite, strong) NSMutableArray *dataSource;
@end

@implementation WYMomentItemViewModel

-(instancetype)initWithMoment:(WYMoment *)moment
{
    if (self = [super init]) {
        
        self.moment = moment;
        
        /// 内容宽度
        CGFloat limitWidth = WYMomentCommentViewWidth();
        /// 单行文字公有一个container
        YYTextContainer *singleRowContainer = [YYTextContainer containerWithSize:YYTextContainerMaxSize];
        singleRowContainer.maximumNumberOfRows = 1;
        /// 高亮背景
        YYTextBorder *border = [YYTextBorder new];
        border.cornerRadius = 0;
        border.insets = UIEdgeInsetsMake(0, -1, 0, -1);
        border.fillColor = TextHighlightBackgroundColor;
        
        //昵称
        if (moment.user.screenName != nil && moment.user.screenName.length > 0) {
            /// 富文本
            NSMutableAttributedString *screenNameAttr = [[NSMutableAttributedString alloc] initWithString:moment.user.screenName];
            screenNameAttr.font = WYMomentScreenNameFont;
            screenNameAttr.color = MomentScreenNameTextColor;
            screenNameAttr.alignment = NSTextAlignmentLeft;
            screenNameAttr.lineBreakMode = NSLineBreakByCharWrapping;
            /// 设置高亮
            YYTextHighlight *highlight = [YYTextHighlight new];
            /// 传递点击事件需要的数据
            highlight.userInfo = @{WYMomentUserInfoKey:moment.user};
            [highlight setBackgroundBorder:border];
            [screenNameAttr setTextHighlight:highlight range:screenNameAttr.rangeOfAll];
            /// 实现布局好宽高 以及属性
            YYTextContainer *screenNameLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
            screenNameLableContainer.maximumNumberOfRows = 1;
            YYTextLayout *screenNameLableLayout = [YYTextLayout layoutWithContainer:screenNameLableContainer text:screenNameAttr.copy];
            self.screenNameLableLayout = screenNameLableLayout;
        }
        
        //内容
        if (moment.text != nil && moment.text.length > 0) {
            NSMutableAttributedString *textAttr = [[NSMutableAttributedString alloc] initWithString:moment.text];
            textAttr.font = WYMomentContentFont;
            textAttr.color = [UIColor blackColor];
            textAttr.lineBreakMode = NSLineBreakByCharWrapping;
            textAttr.alignment = NSTextAlignmentLeft;
            
            /// 实现布局好宽高 以及属性
            /// PS:用这个方法计算尺寸 要比 [self.textAttr mh_sizeWithLimitWidth:limitWidth]这个计算的值要准确的多
            YYTextContainer *contentLableContainer = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
            contentLableContainer.maximumNumberOfRows = 0;
            YYTextLayout *contentLableLayout = [YYTextLayout layoutWithContainer:contentLableContainer text:textAttr.copy];
            self.contentLableLayout = contentLableLayout;
        }
        
        //位置
        if (moment.location != nil && moment.location.length) {
            /// 富文本
            NSMutableAttributedString *location  = [[NSMutableAttributedString alloc] initWithString:moment.location];
            location.font = WYMomentCreatedAtFont;
            location.color = MomentScreenNameTextColor;
            /// 高亮
            YYTextHighlight *highlight = [YYTextHighlight new];
            [highlight setBackgroundBorder:border];
            /// 传递数据
            highlight.userInfo = @{WYMomentLocationNameKey : moment.location};
            /// 布局
            YYTextLayout *locationLableLayout = [YYTextLayout layoutWithContainer:singleRowContainer text:location.copy];
            self.locationLableLayout = locationLableLayout;
        }
        
        //时间
        if (moment.createdAt != nil) {
            NSString *timeStr = [WYMomentHelper createdAtTimeWithSourceDate:moment.createdAt];
            if (timeStr != nil && timeStr.length > 0) {
                NSMutableAttributedString *createdAtAttr = [[NSMutableAttributedString alloc] initWithString:timeStr];
                createdAtAttr.font = WYMomentCreatedAtFont;
                createdAtAttr.color = MomentCreatedAtTextColor;
                /// 布局
                YYTextLayout *createAtLableLayout = [YYTextLayout layoutWithContainerSize:CGSizeMake(MAXFLOAT, MAXFLOAT) text:createdAtAttr];
                self.createAtLableLayout = createAtLableLayout;
            }
        }
        
        //来源
        if (moment.source != nil && moment.source.length > 0) {
            NSMutableAttributedString *source  = [[NSMutableAttributedString alloc] initWithString:moment.source];
            source.font = WYMomentCreatedAtFont;
            source.color = MomentScreenNameTextColor;
            if (self.moment.sourceAllowClick > 0 && self.moment.sourceUrl.length>0) {
                /// 允许点击
                source.color = MomentScreenNameTextColor;
                YYTextHighlight *highlight = [YYTextHighlight new];
                [highlight setBackgroundBorder:border];
                /// 传递数据
                if (self.moment.sourceUrl) highlight.userInfo = @{WYMomentLinkUrlKey : self.moment.sourceUrl};
                [source setTextHighlight:highlight range:source.rangeOfAll];
            }
            
            YYTextLayout *sourceLableLayout = [YYTextLayout layoutWithContainer:singleRowContainer text:source.copy];
            self.sourceLableLayout = sourceLableLayout;
        }
        
        //// 点赞列表
        if (moment.attitudesList.count > 0) {
            WYMomentAttitudesItemViewModel *attitudes = [[WYMomentAttitudesItemViewModel alloc] initWithMoment:moment];
            [self.dataSource addObject:attitudes];
        }
        for (WYComment *comment in moment.commentsList) {
            WYMomentCommentItemViewModel *commentItem = [[WYMomentCommentItemViewModel alloc] initWithComment:comment];
            [self.dataSource addObject:commentItem];
        }
        /// ----------- 尺寸属性 -----------
        /// 头像
        CGFloat avatarViewX = WYMomentContentLeftOrRightInset;
        CGFloat avatarViewY = WYMomentContentTopInset;
        CGFloat avatarViewW = WYMomentAvatarWH;
        CGFloat avatarViewH = WYMomentAvatarWH;
        self.avatarViewFrame = CGRectMake(avatarViewX, avatarViewY, avatarViewW, avatarViewH);
        
        /// 昵称
        CGFloat screenNameLableX = CGRectGetMaxX(self.avatarViewFrame)+WYMomentContentInnerMargin;
        CGFloat screenNameLableY = avatarViewY;
        CGFloat screenNameLableW = self.screenNameLableLayout.textBoundingSize.width;
        CGFloat screenNameLableH = self.screenNameLableLayout.textBoundingSize.height;
        self.screenNameLableFrame = CGRectMake(screenNameLableX, screenNameLableY, screenNameLableW, screenNameLableH);
        
        /*
        /// 正文
        CGFloat contentLableX = self.screenNameLableFrame.origin.x;
        /// -4 修正间距
        CGFloat contentLableY = CGRectGetMaxY(self.screenNameLableFrame)+WYMomentContentInnerMargin-4;
        CGFloat contentLableW = self.contentLableLayout.textBoundingSize.width;
        CGFloat contentLableH = self.contentLableLayout.textBoundingSize.height;
        self.contentLableFrame = CGRectMake(contentLableX, contentLableY, contentLableW, contentLableH);
        
        /// pictureView
        CGFloat pictureViewX = contentLableX;
        CGFloat pictureViewY = CGRectGetMaxY(_contentLableFrame) + WYMomentContentInnerMargin;
        CGSize pictureViewSize = [self pictureViewSizeWithPhotosCount:moment.picInfos.count];
        self.photosViewFrame = (CGRect){{pictureViewX , pictureViewY},pictureViewSize};
        */
        [self updateSubviewsFrameWithExpand:NO];
        
//        self.height = CGRectGetMaxY(self.photosViewFrame) + WYMomentContentInnerMargin;
    }
    return self;
}



/**
 更新内部控件尺寸模型 （点击全文or收起）
 @param expand 全文/收起
 */
- (void)updateSubviewsFrameWithExpand:(BOOL)expand{
    self.expand = expand;
    
    CGFloat limitWidth = WYMomentCommentViewWidth();
    /// 正文
    CGFloat contentLableX = self.screenNameLableFrame.origin.x;
    /// -4 修正间距
    CGFloat contentLableY = CGRectGetMaxY(self.screenNameLableFrame)+WYMomentContentInnerMargin-4;
    /// 需要计算正文的size default 正文为空
    CGSize contentLableSize = CGSizeZero;
    
    /// 全文/收起按钮
    CGFloat expandBtnX = contentLableX;
    /// 这里事先设置
    CGFloat expandBtnY = contentLableY;
    CGFloat expandBtnW = WYMomentExpandButtonWidth;
    CGFloat expandBtnH = 0;
    
    /// 这里要分情况
    YYTextContainer *container = [YYTextContainer containerWithSize:CGSizeMake(limitWidth, MAXFLOAT)];
    YYTextLayout *layout = nil;
    if (self.moment.text != nil && self.moment.text.length > 0) {
        
        /// 显示部分正文 （按钮显示 `全文`）(默认是全部显示)
        contentLableSize = self.contentLableLayout.textBoundingSize;
        if (self.contentLableLayout.rowCount > WYMomentContentTextMaxCriticalRow) {
            /// 容错
            self.expand = NO;
            /// 就显示单行
            container.maximumNumberOfRows = 1;
            layout = [YYTextLayout layoutWithContainer:container text:self.contentLableLayout.text];
            /// 全文/收起 高度为0
            expandBtnH = .0f;
        }else if(self.contentLableLayout.rowCount > WYMomentContentTextExpandCriticalRow){
            /// 重新计算
            if(!expand){
            /// 点击收起 -- 显示全文
                container.maximumNumberOfRows = WYMomentContentTextExpandCriticalRow;
                layout = [YYTextLayout layoutWithContainer:container text:self.contentLableLayout.text];
                contentLableSize = layout.textBoundingSize;
            }
            /// 全文/收起 高度
            expandBtnH = WYMomentExpandButtonHeight;
        }
        /// 全文/收起Y
        expandBtnY = contentLableY + contentLableSize.height + WYMomentContentInnerMargin;
    }
    
    /// 正文
    self.contentLableFrame = CGRectMake(contentLableX, contentLableY, contentLableSize.width, contentLableSize.height);
    
    /// 全文/收起
    self.expandBtnFrame = CGRectMake(expandBtnX, expandBtnY, expandBtnW, expandBtnH);
    
    /// pictureView
    CGFloat pictureViewX = contentLableX;
    CGFloat pictureViewTopMargin = (expandBtnH>0)?WYMomentContentInnerMargin:0;
    CGFloat pictureViewY = CGRectGetMaxY(_expandBtnFrame) + pictureViewTopMargin;
    CGSize pictureViewSize = [self pictureViewSizeWithPhotosCount:self.moment.picInfos.count];
    self.photosViewFrame = (CGRect){{pictureViewX , pictureViewY},pictureViewSize};
    
    /// 分享View
    self.shareInfoViewFrame = (self.moment.type == WYMomentExtendTypeShare) ? CGRectMake(pictureViewX, pictureViewY, (Screen_Width - pictureViewX - WYMomentContentLeftOrRightInset) , WYMomentShareInfoViewHeight) : CGRectZero;
    
    /// videoView
    self.videoViewFrame = (self.moment.type == WYMomentExtendTypeVideo) ? CGRectMake(pictureViewX, pictureViewY, WYMomentVideoViewWidth , WYMomentVideoViewHeight) : CGRectZero;
    
    /// 地理位置
    CGFloat locationLableX = contentLableX;
    /// 顶部
    CGFloat locationLabelTopMargin = (pictureViewSize.height>0)?WYMomentContentInnerMargin:0;
    
    /// 计算高度
    CGFloat locationLableTempMaxY = MAX(CGRectGetMaxY(self.photosViewFrame), CGRectGetMaxY(self.shareInfoViewFrame));
    CGFloat locationLableY = MAX(locationLableTempMaxY, CGRectGetMaxY(self.videoViewFrame)) + locationLabelTopMargin;
    self.locationLableFrame = CGRectMake(locationLableX, locationLableY, self.locationLableLayout.textBoundingSize.width, self.locationLableLayout.textBoundingSize.height);
    
    /// 更多按钮
    CGFloat operationMoreBtnX = Screen_Width - WYMomentContentLeftOrRightInset - WYMomentOperationMoreBtnWH +(WYMomentOperationMoreBtnWH - 25)*.5f;
    CGFloat operationMoreBtnTopMargin = (self.locationLableFrame.size.height>0)?(WYMomentContentInnerMargin-5):0;
    CGFloat operationMoreBtnY = CGRectGetMaxY(self.locationLableFrame)+operationMoreBtnTopMargin;
    CGFloat operationMoreBtnW = WYMomentOperationMoreBtnWH;
    CGFloat operationMoreBtnH = WYMomentOperationMoreBtnWH;
    self.operationMoreBtnFrame = CGRectMake(operationMoreBtnX, operationMoreBtnY, operationMoreBtnW, operationMoreBtnH);
    
    /// 时间
    CGFloat createAtLableX = self.screenNameLableFrame.origin.x;
    CGFloat createAtLableY = self.operationMoreBtnFrame.origin.y;
    self.createAtLableFrame = (CGRect){{ createAtLableX, createAtLableY},{self.createAtLableLayout.textBoundingSize.width,self.operationMoreBtnFrame.size.height}};
    //位置
    if (self.sourceLableLayout != nil) {
        CGFloat sourceLableX = CGRectGetMaxX(self.createAtLableFrame) + WYMomentContentInnerMargin;
        CGFloat sourceLableY = self.operationMoreBtnFrame.origin.y;
        CGSize sourceLableSize = self.sourceLableLayout.textBoundingSize;
        self.sourceLableFrame = (CGRect){{sourceLableX, sourceLableY}, {sourceLableSize.width, self.operationMoreBtnFrame.size.height}};
    }
    self.height = CGRectGetMaxY(self.operationMoreBtnFrame) + WYMomentContentInnerMargin;
}

// pictureView的整体size
- (CGSize)pictureViewSizeWithPhotosCount:(NSUInteger)photosCount{
    
    if (photosCount == 0) return CGSizeZero;
    
    /// 考虑屏幕尺寸为 320的情况
    CGFloat pictureViewItemWH = WYMomentPhotosViewItemWidth();
    /// 这里需要考虑一张图片等比显示的情况
    if(photosCount==1){
        CGSize picSize = CGSizeZero;
        CGFloat maxWidth = WYMomentPhotosViewSingleItemMaxWidth();
        CGFloat maxHeight = WYMomentPhotosViewSingleItemMaxHeight;
        
        WYPicture *pic = self.moment.picInfos.firstObject;
        WYPictureMetadata *bmiddle = pic.bmiddle;
        if (pic.keepSize || bmiddle.width < 1 || bmiddle.height < 1) {
            /// 固定方形
            picSize = CGSizeMake(maxWidth, maxWidth);
        }else{
            if (bmiddle.width < bmiddle.height) {
                picSize.width = (float)bmiddle.width / (float)bmiddle.height * maxHeight;
                picSize.height = maxHeight;
            }else{
                picSize.width = maxWidth;
                picSize.height = (float)bmiddle.height / (float)bmiddle.width * maxWidth;
            }
        }
        return picSize;
    }
    
    /// 大于1的情况 统统显示 九宫格样式
    NSUInteger maxCols = WYMomentMaxCols(photosCount);
    
    // 总列数
    NSUInteger totalCols = photosCount >= maxCols ?  maxCols : photosCount;
    
    // 总行数
    NSUInteger totalRows = (photosCount + maxCols - 1) / maxCols;
    // 计算尺寸
    CGFloat photosW = totalCols * pictureViewItemWH + (totalCols - 1) * WYMomentPhotosViewItemInnerMargin;
    CGFloat photosH = totalRows * pictureViewItemWH + (totalRows - 1) * WYMomentPhotosViewItemInnerMargin;
    return CGSizeMake(photosW, photosH);
    return CGSizeZero;
}

-(NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
@end
